package com.oswift.cms.web.backstage;

import java.awt.image.BufferedImage;
import java.io.File;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.oswift.cms.entity.AdminBean;
import com.oswift.cms.entity.ArticleBean;
import com.oswift.cms.entity.ChannelBean;
import com.oswift.cms.entity.CommonModelBean;
import com.oswift.cms.entity.DictionaryBean;
import com.oswift.cms.entity.ErrorBean;
import com.oswift.cms.entity.MessageBean;
import com.oswift.cms.entity.PageBean;
import com.oswift.cms.entity.WebConfigBean;
import com.oswift.cms.service.IArticleService;
import com.oswift.cms.service.IChannelService;
import com.oswift.cms.service.IPicService;
import com.oswift.cms.service.IWebConfigService;
import com.oswift.cms.system.cache.CMSCacheFileds;
import com.oswift.cms.system.cache.DictionaryManager;
import com.oswift.cms.utils.Field;
import com.oswift.cms.utils.PageCode;
import com.oswift.cms.utils.Field.PageName;
import com.oswift.utils.cache.ResourceManager;
import com.oswift.utils.common.HtmlUtils;
import com.oswift.utils.common.ImageUtils;
import com.oswift.utils.common.StringUtil;
import com.oswift.utils.common.TimeUtil;
import com.oswift.utils.exception.PlatException;

@Controller
@RequestMapping("/security")
public class ArticleAction extends BaseAction
{
    /**
     * 日志实例
     */
    private static Logger log = LoggerFactory.getLogger(ArticleAction.class);

    /**
     * ArticleServiceImpl注入对象
     */
    @Resource
    private IArticleService articleService;

    /**
     * ChannelServiceImpl注入对象
     */
    @Resource
    private IChannelService channelService;

    /**
     * spring对象WebConfigService注入
     */
    @Resource
    private IWebConfigService webConfigService;

    /**
     * PicServiceImpl注入对象
     */
    @Resource
    private IPicService picService;

    /**
     *
     * 加载文章新增页面
     *
     * @author zhuou
     */
    @RequestMapping(value = "/loadAddArticle", method = RequestMethod.GET)
    public ModelAndView loadAddArticle(HttpServletRequest request)
    {
        ModelAndView mv = null;
        try
        {
            AdminBean adminBean = this.getAdmin(request);
            int companyId = adminBean.getCompanyID();

            mv = articleService.loadAddArticle(PageName.ARTICLE, companyId);
            mv.addObject(METHOD, METHOD_ADD);
        }
        catch (PlatException e)
        {
            log.error("The method of loadAddArticle is error.", e);
            mv = new ModelAndView(PageName.ERROR_PAGE);
            ErrorBean bean = new ErrorBean();
            bean.setCode(e.getExceptionCode());
            bean.setMessInfo(ResourceManager.getValue(e.getExceptionCode()));
            mv.addObject("bean", bean);
        }
        catch (Exception e)
        {
            log.error("The method of loadAddArticle is system's error.", e);
            mv = new ModelAndView(PageName.ERROR_PAGE);
            ErrorBean bean = new ErrorBean();
            bean.setCode(PageCode.SYSTEM_ERROR);
            bean.setMessInfo(ResourceManager.getValue(PageCode.SYSTEM_ERROR)
                    + e.getMessage());
            mv.addObject("bean", bean);
        }
        return mv;
    }

    /**
     *
     * 加载文章修改页面
     *
     * @author zhuou
     */
    @RequestMapping(value = "/loadUpdateArticle", method = RequestMethod.GET)
    public ModelAndView loadUpdateArticle(HttpServletRequest request)
    {
        ModelAndView mv = null;
        try
        {
            String id = request.getParameter("id");
            if (StringUtil.isEmpty(id))
            {
                mv = new ModelAndView(PageName.ERROR_PAGE);
                ErrorBean bean = new ErrorBean();
                bean.setCode(PageCode.GET_WEBPARAM_FAIL);
                bean.setMessInfo(ResourceManager
                        .getValue(PageCode.GET_WEBPARAM_FAIL));
                mv.addObject("bean", bean);
                return mv;
            }
            AdminBean adminBean = this.getAdmin(request);
            int companyId = adminBean.getCompanyID();

            mv = articleService.loadUpdateArticle(PageName.ARTICLE, companyId,
                    Integer.valueOf(id));
            mv.addObject(METHOD, METHOD_UPDATE);
        }
        catch (PlatException e)
        {
            log.error("The method of loadUpdateArticle is error.", e);
            mv = new ModelAndView(PageName.ERROR_PAGE);
            ErrorBean bean = new ErrorBean();
            bean.setCode(e.getExceptionCode());
            bean.setMessInfo(ResourceManager.getValue(e.getExceptionCode()));
            mv.addObject("bean", bean);
        }
        catch (Exception e)
        {
            log.error("The method of loadUpdateArticle is system's error.", e);
            mv = new ModelAndView(PageName.ERROR_PAGE);
            ErrorBean bean = new ErrorBean();
            bean.setCode(PageCode.SYSTEM_ERROR);
            bean.setMessInfo(ResourceManager.getValue(PageCode.SYSTEM_ERROR)
                    + e.getMessage());
            mv.addObject("bean", bean);
        }
        return mv;
    }

    /**
     *
     * 添加文章信息
     *
     * @author zhuou
     */
    @RequestMapping(value = "/addArticle", method = RequestMethod.POST)
    @ResponseBody
    public Object addArticle(HttpServletRequest request, ArticleBean bean)
    {
        MessageBean messBean = new MessageBean();
        try
        {
            if (StringUtil.isEmpty(bean.getTitle())
                    || StringUtil.isEmpty(bean.getContent())
                    || bean.getChannelId() <= 0)
            {
                messBean.setCode(PageCode.TEXTFIELD_ISNOT_EMPTY);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.TEXTFIELD_ISNOT_EMPTY));
                return messBean;
            }
            AdminBean adminBean = this.getAdmin(request);
            bean.setCompanyId(adminBean.getCompanyID());
            bean.setTableName(Field.TableName.ARTICLE);
            bean.setInputer(adminBean.getAdminName());

            // 查看内容中有多少图片
            List<String> imgList = HtmlUtils.getImgSrcFromHtml(bean
                    .getContent());
            bean.setContentImgNum(imgList.size());

            if (StringUtil.isBlank(bean.getFocusImg()))
            {
                bean.setFocusImgNum(0);
            }
            else
            {
                bean.setFocusImgNum(1);
            }
            if (StringUtil.isBlank(bean.getBigNewsImg()))
            {
                bean.setBigNewsImgNum(0);
            }
            else
            {
                bean.setBigNewsImgNum(1);
            }
            if (StringUtil.isBlank(bean.getMarqueeImg()))
            {
                bean.setMarqueeImgNum(0);
            }
            else
            {
                bean.setMarqueeImgNum(1);
            }
            if (StringUtil.isBlank(bean.getDefaultPicUrl()))
            {
                // 如果为空则将内容的图片缩略作为封面
                String imgUrl = null;
                if (imgList.size() > 0)
                {
                    // 取图片,去地址为空的第一张图片
                    for (String img : imgList)
                    {
                        if (!StringUtil.isBlank(img))
                        {
                            imgUrl = img;
                            break;
                        }
                    }

                    // 生成缩略图
                    bean.setDefaultPicUrl(thumbImg(request, adminBean, bean
                            .getTitle(), imgUrl));
                }
                else
                {
                    bean.setDefaultPicUrl(null);
                }
            }

            boolean isSuccess = articleService.save(bean);
            if (isSuccess)
            {
                messBean.setCode(PageCode.COMMON_SUCCESS);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.ARTICLE_ADD_SUCCESS));
            }
            else
            {
                messBean.setCode(PageCode.ARTICLE_ADD_FAIL);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.ARTICLE_ADD_FAIL));
            }
        }
        catch (PlatException e)
        {
            log.error("The method of addArticle is error.", e);
            messBean.setCode(e.getExceptionCode());
            messBean.setContent(ResourceManager.getValue(e.getExceptionCode()));
        }
        catch (Exception e)
        {
            log.error("The method of addArticle is system's error.", e);
            messBean.setCode(PageCode.SYSTEM_ERROR);
            messBean.setContent(ResourceManager.getValue(PageCode.SYSTEM_ERROR)
                    + e.getMessage());
        }
        return messBean;
    }

    /**
     *
     * 将内容图片根据设置生成缩略图并保存到默认封面字段中
     *
     * @author zhuou
     * @param imgUrl
     *            图片地址
     * @return String
     */
    private String thumbImg(HttpServletRequest request, AdminBean adminBean,
            String title, String imgUrl)
    {
        if (StringUtil.isBlank(imgUrl))
        {
            return null;
        }

        // 处理后的图片存储的相对路径
        String imgRelativeUrl = null;
        try
        {
            String imgRealPath = null, toSavePath = null;
            // 是网络图片还是本地图片
            if (imgUrl.indexOf(Field.HTTP) != -1)
            {
                // 是网络图片下载
                MessageBean message = picService.download(request, imgUrl,
                        adminBean.getCompanyID(), title);
                if (null != message
                        && PageCode.COMMON_SUCCESS.equals(message.getCode()))
                {
                    imgRealPath = (String) message.getObjContent();
                    toSavePath = imgRealPath;

                    // 获取相对路径
                    imgRelativeUrl = message.getContent();
                }
            }
            // 本地图片
            else
            {
                // 将图片路径copy一份
                imgRelativeUrl = new String(imgUrl);
                String contextPath = request.getContextPath();
                if (!StringUtil.isBlank(contextPath))
                {
                    // 如果网站有根目录，则将根目录从路径中去掉
                    imgUrl = imgUrl.substring(contextPath.length());
                }

                // 获取图片在磁盘的绝对路径
                imgRealPath = request.getSession().getServletContext()
                        .getRealPath(imgUrl);

                String oldName = getFileName(imgRealPath);
                String newName = TimeUtil.dateToString(new Date(),
                        TimeUtil.COMPACT_DATE_TIME_MS_FORMAT);

                toSavePath = imgRealPath.replace(oldName, newName);
                imgRelativeUrl = imgRelativeUrl.replace(oldName, newName);
            }
            if (StringUtil.isBlank(imgRealPath)
                    || StringUtil.isBlank(toSavePath))
            {
                return null;
            }

            // 获取网站关于缩略图的参数配置
            int imgThumbWidth = 100, imgThumbHeight = 100;
            WebConfigBean webBean = webConfigService.getWebConfigById(getAdmin(
                    request).getSiteId());
            if (null == webBean)
            {
                return null;
            }
            if (webBean.getImgThumbWidth() > 0)
            {
                imgThumbWidth = webBean.getImgThumbWidth();
            }
            if (webBean.getImgThumbHeight() > 0)
            {
                imgThumbHeight = webBean.getImgThumbHeight();
            }

            // 下面是判断此图片是否适合生产缩略图，如果不适合则不生成
            // 算出要缩略图比例
            double dImgThumbWidth = new BigDecimal(imgThumbWidth).doubleValue();
            double dImgThumbHeight = new BigDecimal(imgThumbHeight)
                    .doubleValue();
            double scale = dImgThumbWidth / dImgThumbHeight;
            // 误差比例
            double errorScale = 0.3;

            // 实际图片的比例
            File f = new File(imgRealPath);
            BufferedImage bi = ImageIO.read(f);
            double dImgWidth = new BigDecimal(bi.getWidth()).doubleValue();
            double dImgHeight = new BigDecimal(bi.getHeight()).doubleValue();
            double imgScale = dImgWidth / dImgHeight;

            // 上下误差0.5
            if (imgScale > (scale - errorScale)
                    && imgScale < (scale + errorScale))
            {
                // 压缩图片，生成缩略图
                ImageUtils.scale2(imgRealPath, toSavePath, imgThumbHeight,
                        imgThumbWidth, true);

                return imgRelativeUrl;
            }
        }
        catch (Exception e)
        {
            log.error("The method of thumbImg is system's error.", e);
        }
        return null;
    }

    /**
     *
     * 获取图片名称
     *
     * @author zhuou
     * @param filePath
     *            图片
     * @return String
     */
    private String getFileName(String filePath)
    {
        File tempFile = new File(filePath.trim());
        String fileName = tempFile.getName();

        return fileName.substring(0, fileName.lastIndexOf('.'));
    }

    /**
     *
     * 修改文章信息
     *
     * @author zhuou
     */
    @RequestMapping(value = "/updateArticle", method = RequestMethod.POST)
    @ResponseBody
    public Object updateArticle(HttpServletRequest request, ArticleBean bean)
    {
        MessageBean messBean = new MessageBean();
        try
        {
            if (bean.getCommonModelId() <= 0)
            {
                messBean.setCode(PageCode.GET_WEBPARAM_FAIL);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.GET_WEBPARAM_FAIL));
                return messBean;
            }

            if (StringUtil.isEmpty(bean.getTitle())
                    || StringUtil.isEmpty(bean.getContent())
                    || bean.getChannelId() <= 0)
            {
                messBean.setCode(PageCode.TEXTFIELD_ISNOT_EMPTY);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.TEXTFIELD_ISNOT_EMPTY));
                return messBean;
            }
            // 查看内容中有多少图片
            List<String> imgList = HtmlUtils.getImgSrcFromHtml(bean
                    .getContent());
            bean.setContentImgNum(imgList.size());

            if (StringUtil.isBlank(bean.getFocusImg()))
            {
                bean.setFocusImgNum(0);
            }
            else
            {
                bean.setFocusImgNum(1);
            }
            if (StringUtil.isBlank(bean.getBigNewsImg()))
            {
                bean.setBigNewsImgNum(0);
            }
            else
            {
                bean.setBigNewsImgNum(1);
            }
            if (StringUtil.isBlank(bean.getMarqueeImg()))
            {
                bean.setMarqueeImgNum(0);
            }
            else
            {
                bean.setMarqueeImgNum(1);
            }
            if (StringUtil.isBlank(bean.getDefaultPicUrl()))
            {
                // 如果为空则将内容的图片缩略作为封面
                String imgUrl = null;
                if (imgList.size() > 0)
                {
                    // 取图片,去地址为空的第一张图片
                    for (String img : imgList)
                    {
                        if (!StringUtil.isBlank(img))
                        {
                            imgUrl = img;
                            break;
                        }
                    }
                    AdminBean adminBean = this.getAdmin(request);
                    // 生成缩略图
                    bean.setDefaultPicUrl(thumbImg(request, adminBean, bean
                            .getTitle(), imgUrl));
                }
                else
                {
                    bean.setDefaultPicUrl(null);
                }
            }

            boolean isSuccess = articleService.update(bean);
            if (isSuccess)
            {
                messBean.setCode(PageCode.COMMON_SUCCESS);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.ARTICLE_UPDATE_SUCCESS));
            }
            else
            {
                messBean.setCode(PageCode.ARTICLE_UPDATE_FAIL);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.ARTICLE_UPDATE_FAIL));
            }
        }
        catch (PlatException e)
        {
            log.error("The method of updateArticle is error.", e);
            messBean.setCode(e.getExceptionCode());
            messBean.setContent(ResourceManager.getValue(e.getExceptionCode()));
        }
        catch (Exception e)
        {
            log.error("The method of updateArticle is system's error.", e);
            messBean.setCode(PageCode.SYSTEM_ERROR);
            messBean.setContent(ResourceManager.getValue(PageCode.SYSTEM_ERROR)
                    + e.getMessage());
        }
        return messBean;
    }

    /**
     *
     * 删除文章信息
     *
     * @author zhuou
     */
    @RequestMapping(value = "/delArticle", method = RequestMethod.POST)
    @ResponseBody
    public Object delArticle(HttpServletRequest request)
    {
        MessageBean messBean = new MessageBean();
        try
        {
            String id = request.getParameter("id");
            if (StringUtil.isEmpty(id))
            {
                messBean.setCode(PageCode.GET_WEBPARAM_FAIL);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.GET_WEBPARAM_FAIL));
                return messBean;
            }

            int delSuccessNum = 0;
            int delFailNum = 0;
            String[] array = id.split(Field.COMMA);
            for (String i : array)
            {
                boolean isSuccess = articleService.delete(Integer.valueOf(i));
                if (isSuccess)
                {
                    delSuccessNum++;
                }
                else
                {
                    delFailNum++;
                }
            }

            if (delSuccessNum == array.length)
            {
                messBean.setCode(PageCode.COMMON_SUCCESS);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.ARTICLE_DEL_SUCCESS));
            }
            else
            {
                messBean.setCode(PageCode.ARTICLE_DEL_FAIL);
                String mess = ResourceManager
                        .getValue(PageCode.ARTICLE_DEL_FAIL);
                messBean.setContent(StringUtil.replace(mess, String
                        .valueOf(delSuccessNum), String.valueOf(delFailNum)));
            }
        }
        catch (PlatException e)
        {
            log.error("The method of delArticle is error.", e);
            messBean.setCode(e.getExceptionCode());
            messBean.setContent(ResourceManager.getValue(e.getExceptionCode()));
        }
        catch (Exception e)
        {
            log.error("The method of delArticle is system's error.", e);
            messBean.setCode(PageCode.SYSTEM_ERROR);
            messBean.setContent(ResourceManager.getValue(PageCode.SYSTEM_ERROR)
                    + e.getMessage());
        }
        return messBean;
    }

    /**
     *
     * 文章详情
     *
     * @author zhuou
     */
    @RequestMapping(value = "/articleDetail", method = RequestMethod.GET)
    public ModelAndView articleDetail(HttpServletRequest request)
    {
        ModelAndView mv = null;
        try
        {
            String id = request.getParameter("id");
            if (StringUtil.isEmpty(id))
            {
                mv = new ModelAndView(PageName.ERROR_PAGE);
                ErrorBean bean = new ErrorBean();
                bean.setCode(PageCode.GET_WEBPARAM_FAIL);
                bean.setMessInfo(ResourceManager
                        .getValue(PageCode.GET_WEBPARAM_FAIL));
                mv.addObject("bean", bean);
                return mv;
            }

            ArticleBean bean = articleService.getOne(Integer.valueOf(id));
            mv = new ModelAndView(PageName.ARTICLE_DETAIL);
            mv.addObject("articleBean", bean);
        }
        catch (PlatException e)
        {
            log.error("The method of articleDetail is error.", e);
            mv = new ModelAndView(PageName.ERROR_PAGE);
            ErrorBean bean = new ErrorBean();
            bean.setCode(e.getExceptionCode());
            bean.setMessInfo(ResourceManager.getValue(e.getExceptionCode()));
            mv.addObject("bean", bean);
        }
        catch (Exception e)
        {
            log.error("The method of articleDetail is system's error.", e);
            mv = new ModelAndView(PageName.ERROR_PAGE);
            ErrorBean bean = new ErrorBean();
            bean.setCode(PageCode.SYSTEM_ERROR);
            bean.setMessInfo(ResourceManager.getValue(PageCode.SYSTEM_ERROR)
                    + e.getMessage());
            mv.addObject("bean", bean);
        }
        return mv;
    }

    /**
     *
     * 获取公共内容信息
     *
     * @author zhuou
     */
    @RequestMapping(value = "/getArticleList", method = RequestMethod.GET)
    public ModelAndView getArticleList(HttpServletRequest request)
    {
        ModelAndView mv = null;
        try
        {
            String orderField = request.getParameter("orderField");
            String orderType = request.getParameter("orderType");
            String s_Status = request.getParameter("status");
            String s_ChannelId = request.getParameter("channelId");
            String searchType = request.getParameter("searchType");
            String keyword = request.getParameter("keyword");
            String s_PageNum = request.getParameter("pageNum");

            int status = Field.Status.ALL;
            if (!StringUtil.isEmpty(s_Status))
            {
                status = Integer.valueOf(s_Status);
            }
            int channelId = -1;
            if (!StringUtil.isEmpty(s_ChannelId))
            {
                channelId = Integer.valueOf(s_ChannelId);
            }
            int pageNum = DEFAULT_PAGENUM;
            if (!StringUtil.isEmpty(s_PageNum))
            {
                pageNum = Integer.valueOf(s_PageNum);
            }

            // 权限判断
            AdminBean adminBean = this.getAdmin(request);
            int companyId = adminBean.getCompanyID();

            PageBean<CommonModelBean> bean = articleService.getCommonModel(
                    orderField, orderType, status, channelId, searchType,
                    keyword, this.pageRecordNum, pageNum,
                    Field.TableName.ARTICLE, companyId);
            mv = new ModelAndView(PageName.ARTICLELIST);

            // 获取包含文章板块的栏目
            DictionaryBean dictionaryBean = DictionaryManager
                    .getValue(CMSCacheFileds.BusinessField.DEFAULT_ARTICLE_KEY);
            List<ChannelBean> channelList = channelService.getChannelList2(
                    companyId, dictionaryBean.getFieldValue());

            mv.addObject("pageBean", bean);
            mv.addObject("status", status);
            mv.addObject("channels", channelList);
            mv.addObject("orderType", orderField + "_" + orderType);
            mv.addObject("channelId", channelId);
        }
        catch (PlatException e)
        {
            log.error("Get ArticleList info is error.", e);
            mv = new ModelAndView(PageName.ERROR_PAGE);
            ErrorBean bean = new ErrorBean();
            bean.setCode(e.getExceptionCode());
            bean.setMessInfo(e.getMessage());
            bean.setUrl("getArticleList.html");
            mv.addObject("bean", bean);
        }

        return mv;
    }

    public void setArticleService(IArticleService articleService)
    {
        this.articleService = articleService;
    }

    public void setChannelService(IChannelService channelService)
    {
        this.channelService = channelService;
    }

    public void setWebConfigService(IWebConfigService webConfigService)
    {
        this.webConfigService = webConfigService;
    }

    public void setPicService(IPicService picService)
    {
        this.picService = picService;
    }
}